package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForwardIos
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Feedback
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.navigation.Routes
import com.hwpt.chesedemo.presentation.theme.AppStrings
import com.hwpt.chesedemo.presentation.theme.LanguageManager
import com.hwpt.chesedemo.presentation.theme.LocalStrings
import com.hwpt.chesedemo.presentation.viewmodel.SettingsViewModel

@Composable
fun SettingsScreen(
    navController: NavController,
    viewModel: SettingsViewModel = viewModel()
) {
    val context = LocalContext.current

    // 使用 CompositionLocalProvider 来提供正确的字符串资源
    CompositionLocalProvider(
        LocalStrings provides AppStrings.getByLanguageCode(viewModel.currentLanguageCode)
    ) {
        val strings = LocalStrings.current

        // 加载语言设置
        LaunchedEffect(Unit) {
            viewModel.loadLanguageSettings(context)
        }

        // 监听 LanguageManager 的变化
        LaunchedEffect(LanguageManager.currentLanguageCode) {
            viewModel.updateLanguageCode(LanguageManager.currentLanguageCode)
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
                    )
                )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                Text(
                    text = strings.settings,
                    fontSize = 28.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.padding(vertical = 32.dp)
                )

                // 语言设置按钮
                SettingsItemCard(
                    title = strings.language,
                    subtitle = viewModel.getCurrentLanguageName(),
                    icon = Icons.Default.Language,
                    onClick = { viewModel.showLanguageDialog() }
                )

                Spacer(modifier = Modifier.height(16.dp))

                // 关于我们按钮
                SettingsItemCard(
                    title = strings.aboutUs,
                    subtitle = strings.aboutUsDescription,
                    icon = Icons.Default.Info,
                    onClick = {
                        navController.navigate("about_us")
                    }
                )

                Spacer(modifier = Modifier.height(16.dp))

                // 意见反馈按钮
                SettingsItemCard(
                    title = strings.feedback,
                    subtitle = strings.feedbackDescription,
                    icon = Icons.Default.Feedback,
                    onClick = {
                        navController.navigate("feedback")
                    }
                )

                Spacer(modifier = Modifier.height(16.dp))


                // 蓝牙连接按钮（使用硬编码中文）
                SettingsItemCard(
                    title = "蓝牙连接",
                    subtitle = "连接智能棋盘设备",
                    icon = Icons.Default.Bluetooth,
                    onClick = {
                        navController.navigate(Routes.BLUETOOTH)  // 使用 Routes.BLUETOOTH
                    }
                )

                Spacer(modifier = Modifier.height(16.dp))
            }

            // 语言选择对话框
            if (viewModel.showLanguageDialog) {
                LanguageSelectionDialog(
                    currentLanguage = viewModel.getCurrentLanguageName(),
                    onLanguageSelected = { languageName ->
                        val languageCode = AppStrings.getLanguageCodeByDisplayName(languageName)
                        viewModel.changeLanguage(context, languageCode)
                    },
                    onDismiss = { viewModel.hideLanguageDialog() }
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsItemCard(
    title: String,
    subtitle: String,
    icon: ImageVector,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(80.dp)
            .border(
                width = 1.dp,
                color = Color.White.copy(alpha = 0.3f),
                shape = RoundedCornerShape(12.dp)
            ),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF5A6EE1)
        ),
        onClick = onClick
    ) {
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = title,
                tint = Color.White,
                modifier = Modifier
                    .width(24.dp)
                    .height(24.dp)
            )

            Spacer(modifier = Modifier.width(16.dp))

            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.White
                )
                Text(
                    text = subtitle,
                    fontSize = 14.sp,
                    color = Color.White.copy(alpha = 0.8f)
                )
            }

            Icon(
                imageVector = Icons.Default.ArrowForwardIos,
                contentDescription = "跳转",
                tint = Color.White,
                modifier = Modifier
                    .width(16.dp)
                    .height(16.dp)
            )
        }
    }
}

@Composable
fun LanguageSelectionDialog(
    currentLanguage: String,
    onLanguageSelected: (String) -> Unit,
    onDismiss: () -> Unit
) {
    val strings = LocalStrings.current
    val supportedLanguages = AppStrings.getSupportedLanguages()

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = strings.selectLanguage,
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp
            )
        },
        text = {
            Column {
                supportedLanguages.forEach { (displayName, _) ->
                    LanguageOption(
                        language = displayName,
                        isSelected = currentLanguage == displayName,
                        onClick = { onLanguageSelected(displayName) }
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text(strings.cancel)
            }
        }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LanguageOption(
    language: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(50.dp),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = if (isSelected) 4.dp else 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) Color(0xFF6A11CB) else Color.White
        ),
        onClick = onClick
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            contentAlignment = Alignment.CenterStart
        ) {
            Text(
                text = language,
                fontSize = 16.sp,
                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                color = if (isSelected) Color.White else Color.Black
            )
        }
    }
}